package com.study.talk.ui.adapter

import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.study.common.MDParser
import com.study.talk.databinding.SmartChatListItemBinding
import com.volcengine.ark.runtime.model.completion.chat.ChatMessage
import com.volcengine.ark.runtime.model.completion.chat.ChatMessageRole

class SmartChatListAdapter(private val data : List<ChatMessage>) :
    RecyclerView.Adapter<SmartChatListAdapter.ViewHolder>() {

    class ViewHolder(val bing: SmartChatListItemBinding) : RecyclerView.ViewHolder(bing.root)

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        return ViewHolder(
            SmartChatListItemBinding.inflate(
                LayoutInflater.from(parent.context),
                parent,
                false
            )
        )
    }

    override fun getItemCount(): Int {
        return data.size
    }

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        val message = data[position]
        if (message.role == ChatMessageRole.USER) {
            holder.bing.smartChatListItemContentLeft.visibility = View.GONE
            holder.bing.smartChatListItemContentRight.visibility = View.VISIBLE
            holder.bing.smartChatListItemContentRight.text = message.content.toString()
        } else {
            holder.bing.smartChatListItemContentRight.visibility = View.GONE
            holder.bing.smartChatListItemContentLeft.visibility = View.VISIBLE
            holder.bing.smartChatListItemContentLeft.text = MDParser.toSpanned(message.content.toString())
        }
    }

    override fun onBindViewHolder(holder: ViewHolder, position: Int, payloads: MutableList<Any>) {
        if (payloads.isNotEmpty()) {
            for (payload in payloads) {
                when (payload) {
                    "contentUpdating" -> {
                        val message = data[position]
                        if (message.role == ChatMessageRole.USER) {
                            holder.bing.smartChatListItemContentRight.text = message.content.toString()
                        }else{
                            holder.bing.smartChatListItemContentLeft.text = message.content.toString()
                        }
                    }
                }
            }
        } else {
            super.onBindViewHolder(holder, position, payloads)
        }
    }
}